package com.linjian.togetherbirthday.activity;


import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import com.google.gson.Gson;
import com.linjian.togetherbirthday.MainActivity;
import com.linjian.togetherbirthday.R;
import com.linjian.togetherbirthday.base.BaseActivity;
import com.linjian.togetherbirthday.fragment.BirthSetFragment;
import com.linjian.togetherbirthday.fragment.ChooseGenderFragment;
import com.linjian.togetherbirthday.fragment.HeightSetFragment;
import com.linjian.togetherbirthday.fragment.LoginFragment;
import com.linjian.togetherbirthday.fragment.NickUserPicFragment;
import com.linjian.togetherbirthday.fragment.RegistFragment;
import com.linjian.togetherbirthday.util.StatusBarCompat;
import com.linjian.togetherbirthday.utils.SharedPreferencesUtil;
import com.yuntongxun.ecsdk.SdkErrorCode;
import com.yuntongxun.plugin.common.AppMgr;
import com.yuntongxun.plugin.common.ClientUser;
import com.yuntongxun.plugin.common.SDKCoreHelper;
import com.yuntongxun.plugin.common.common.utils.ECPreferences;
import com.yuntongxun.plugin.common.common.utils.EasyPermissionsEx;
import com.yuntongxun.plugin.common.common.utils.LogUtil;
import com.yuntongxun.plugin.common.common.utils.ToastUtil;
import com.yuntongxun.plugin.common.ui.RongXinFragmentActivity;
import com.yuntongxun.plugin.greendao3.helper.DaoHelper;
import com.yuntongxun.plugin.im.dao.helper.IMDao;

import java.util.Map;

public class SplashActivity extends BaseActivity implements FragmentManager.OnBackStackChangedListener, View.OnClickListener {

    private LoginFragment loginFragment;
    private RegistFragment registFragment;
    private ChooseGenderFragment chooseGenderFragment;
    private BirthSetFragment birthSetFragment;
    private HeightSetFragment heightSetFragment;
    private NickUserPicFragment nickUserPicFragment;

    private FragmentManager fragmentManager;
    private FragmentTransaction transaction;

    private SharedPreferences sharedPreferences;
    private SharedPreferences.Editor editor;
    private int id;

    private ImageView backIv;

    private String TAG = "SplashActivity";
//    private ECProgressDialog dialog;
//
//    public void showDialog() {
//        if (dialog == null) {
//            dialog = new ECProgressDialog(this, "请稍后...");
//        }
//        dialog.show();
//    }
//
//    private void dismissDialog() {
//        if (dialog != null && dialog.isShowing()) {
//            dialog.dismiss();
//        }
//    }

    private BroadcastReceiver mSDKNotifyReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if (SDKCoreHelper.ACTION_SDK_CONNECT.equals(intent.getAction())) {
                if (SDKCoreHelper.isLoginSuccess(intent)) {
                    String pushToken = ECPreferences.getSharedPreferences().getString("pushToken", null);
                    LogUtil.d(TAG, "SDK connect Success ,reportToken:" + pushToken);
                    if (!TextUtils.isEmpty(pushToken)) {
                        // 上报华为/小米推送设备token
//                        ECDevice.reportHuaWeiToken(pushToken);
                    }
                    Map<String, Object> map = new Gson().fromJson(String.valueOf(SharedPreferencesUtil.get(SplashActivity.this, "LoginInfo", "")), Map.class);
                    if (map!=null) {
                        if (map.get("headImg") != null) {
                            // 初始化IM数据库
                            DaoHelper.init(SplashActivity.this, new IMDao());
//                    dismissDialog();
                            Intent action = new Intent(SplashActivity.this, MainActivity.class);
                            action.putExtra("userid", AppMgr.getUserId());
                            startActivity(action);
                            finish();
                        }
                    }

                } else {
                    int error = intent.getIntExtra("error", 0);
                    if (error == SdkErrorCode.CONNECTING) return;
//                    dismissDialog();
                    LogUtil.e(TAG, "登入失败[" + error + "]");
//                    ToastUtil.showMessage("登入失败[" + error + "]");
                }
            }
        }
    };


    @Override
    protected void initView() {
        setContentView(R.layout.activity_splash);
        StatusBarCompat.translucentStatusBar(this);
        initPermission();
        sharedPreferences = getSharedPreferences("isOne", Context.MODE_PRIVATE);
        id = sharedPreferences.getInt("isLogin", 0);


        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(SDKCoreHelper.ACTION_SDK_CONNECT);
        registerReceiver(mSDKNotifyReceiver, intentFilter);

        if (AppMgr.getClientUser() != null) {
            LogUtil.d(TAG, "SDK auto connect...");
            SDKCoreHelper.init(getApplicationContext());
        }


    }



    @Override
    protected void initData() {
        loginFragment = LoginFragment.newInstance();
        fragmentManager = getSupportFragmentManager();
        transaction = fragmentManager.beginTransaction();
        Map<String, Object> map = new Gson().fromJson(String.valueOf(SharedPreferencesUtil.get(this, "LoginInfo", "")), Map.class);
        if (map!=null) {
            if (map.get("headImg") != null) {
                String account = String.valueOf(SharedPreferencesUtil.get(this,"LoginPhone",""));
                String name = String.valueOf(map.get("nickname"));
                login(account,name);
//                startActivity("HomeOneFragment");
            } else {
                transaction.replace(R.id.splash_fl, loginFragment)
                        .commit();
            }
        }else {
            transaction.replace(R.id.splash_fl, loginFragment)
                    .commit();
        }

        backIv = findViewById(R.id.back);
    }

    @Override
    protected void setEvent() {
        fragmentManager.addOnBackStackChangedListener(this);
        backIv.setOnClickListener(this);
    }

    public void replaceFragment(String frag, String data) {

        transaction = getSupportFragmentManager().beginTransaction();
        transaction.setCustomAnimations(R.anim.enter_scale, R.anim.exit_scale);
        switch (frag) {
            case "LoginFragment":
                loginFragment = LoginFragment.newInstance();
                transaction.replace(R.id.splash_fl, loginFragment);
                break;
            case "RegistFragment":
                registFragment = RegistFragment.newInstance(data);
                transaction.replace(R.id.splash_fl, registFragment);
                transaction.addToBackStack(null);
                break;
            case "ChooseGenderFragment":
                chooseGenderFragment = ChooseGenderFragment.newInstance();
                transaction.replace(R.id.splash_fl, chooseGenderFragment);
                transaction.addToBackStack(null);
                break;
            case "BirthFragment":
                birthSetFragment = BirthSetFragment.newInstance(data);
                transaction.replace(R.id.splash_fl, birthSetFragment);
                transaction.addToBackStack(null);
                break;
            case "HeightSetFragment":
                heightSetFragment = HeightSetFragment.newInstance(data);
                transaction.replace(R.id.splash_fl, heightSetFragment);
                transaction.addToBackStack(null);
                break;
            case "NickUserPicFragment":
                nickUserPicFragment = NickUserPicFragment.newInstance(data);
                transaction.replace(R.id.splash_fl, nickUserPicFragment);
                transaction.addToBackStack(null);
                break;
            default:

                break;
        }

        transaction.commit();
    }

    public void startActivity(String frag) {
        switch (frag) {
            case "PersonalCenterFragment":
                startAnim(frag);
                break;
            case "HomeOneFragment":
                startAnim(frag);
                break;
        }
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        if (fragmentManager != null) {
            if (fragmentManager.getBackStackEntryCount() <= 0) {
                finish();
            } else {
                fragmentManager.popBackStack();
            }
        }
    }

    @Override
    public void onBackStackChanged() {
        if (fragmentManager.getBackStackEntryCount() > 0) {
            backIv.setVisibility(View.VISIBLE);
        } else {
            backIv.setVisibility(View.GONE);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back:
                fragmentManager.popBackStack();
                break;
        }
    }

    /**
     * 过渡动画
     */
    private void startAnim(String frag) {
        startActivity(new Intent(SplashActivity.this, MainActivity.class)
                .putExtra("fragment", frag));
    }

    @Override
    protected void onStop() {
        super.onStop();
        this.finish();
    }


    private String rationInit = "需要存储、相机和麦克风的权限";

    private void initPermission() {
        if (EasyPermissionsEx.hasPermissions(SplashActivity.this, RongXinFragmentActivity.needPermissionsCamera)) {
            LogUtil.d(TAG, "permission is userful");
        } else {
            EasyPermissionsEx.requestPermissions(SplashActivity.this, rationInit, RongXinFragmentActivity.PERMISSIONS_REQUEST_CAMERA, RongXinFragmentActivity.needPermissionsCamera);
        }
    }



    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 注销广播
        unregisterReceiver(mSDKNotifyReceiver);
    }


    public static String getNameById(String id) {
        return "" + id;
    }


    public void login(String account,String name){

        if (TextUtils.isEmpty(account) || TextUtils.isEmpty(name)) {
            ToastUtil.showMessage("ID和名字两者都必须填写");
            return;
        }
//        showDialog();
        ClientUser.UserBuilder builder = new ClientUser.UserBuilder(account, name);
        // 以下setXXX参数都是可选
        // builder.setAppKey("appKey");// AppId(私有云使用)
        // builder.setAppToken("appToken");// AppToken(私有云使用)
        // builder.setPwd(et_pwd.getText().toString());// Password不为空情况即通讯账号密码登入
        // 下面三个参数是调用REST接口使用(如:语音会议一键静音功能)
        // builder.setAccountSid("accountSid");// 主账号Id(REST使用)
        // builder.setAuthToken("autoToken");// 账户授权令牌(REST使用)


        // 公有云使用一个参数login登入
        builder.setRestHost("http://app.cloopen.com:8883");// REST 协议+ip+端口(REST使用)
        builder.setLvsHost("http://app.cloopen.com:8883");
        SDKCoreHelper.login(builder.build());
    }
}
